package com.nlscan.ncomgateway.core.database

import android.content.Context
import androidx.room.Database
import androidx.room.Room
import androidx.room.RoomDatabase
import androidx.room.migration.Migration
import androidx.sqlite.db.SupportSQLiteDatabase
import com.nlscan.ncomgateway.core.database.dao.DeviceDao
import com.nlscan.ncomgateway.core.database.model.DeviceEntity

/**
 * <pre>
 *  author: lin.qing
 *  time  : 2023/3/21
 *  desc  :
 * </pre>
 */
@Database(entities = [DeviceEntity::class], version = 2, exportSchema = true)
abstract class AppDatabase : RoomDatabase() {

    abstract fun deviceDao(): DeviceDao

    companion object {
        @Volatile
        private var INSTANCE: AppDatabase? = null

        @Synchronized
        fun get(context: Context): AppDatabase {
            if (INSTANCE == null) {
                INSTANCE = Room.databaseBuilder(
                    context.applicationContext, AppDatabase::class.java, "db_main"
                )
                    .allowMainThreadQueries()
                    .addMigrations(MIGRATION_1_2)
                    .build()
            }
            return INSTANCE!!
        }

        private val MIGRATION_1_2 = object : Migration(1, 2) {
            override fun migrate(database: SupportSQLiteDatabase) {
                database.execSQL("alter table 'tb_device' add 'serial_number' TEXT NOT NULL DEFAULT ''")
                database.execSQL("alter table 'tb_device' add 'batteryLevel' Int NOT NULL DEFAULT '-1'")
            }
        }
    }


}